﻿using IdentityServer4.Extensions;
using IdentityServer4.Models;
using IdentityServer4.Services;
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
using Windows.Admin.Contract;
using Windows.Admin.Contract.User.Model;
using Windows.Infrastructure.Share.Extensions;
using Windows.Infrastructure.Share.Security;

namespace Windows.Identity.Api
{
    public class ProfileService: IProfileService
    {
        private readonly IUserGrpcService _userService;
        // <summary>
        /// The claims factory.
        /// </summary>
        /// <summary>
        /// Initializes a new instance of the <see cref="TestUserProfileService"/> class.
        /// </summary>
        /// <param name="logger">The logger.</param>
        /// <param name="userRepository"></param>
        public ProfileService(IUserGrpcService userService)
        {
            _userService = userService;
        }

        /// <summary>
        /// 只要有关用户的身份信息单元被请求（例如在令牌创建期间或通过用户信息终点），就会调用此方法
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual async Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            var sub = context.Subject?.GetSubjectId();
            if (sub == null) throw new Exception("No sub claim present");
            UserGrpcRequest info = new UserGrpcRequest();
            info.Id = sub.ToInt();
            var user = await _userService.FindUserAsync(info);
            if (user == null)
            {
                //_logger?.LogWarning("No user found matching subject Id: {0}", sub);
            }
            else
            {
                List<Claim> claims = new()
                {
                    new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),
                    new Claim(ClaimTypes.Name, user.UserName ?? ""),
                    new Claim(ClaimTypes.MobilePhone, user.MobilePhone ?? ""),
                    new Claim(ClaimTypes.Email, user.Email ?? ""),
                    new Claim(ClaimTypes.GivenName, user.Name ?? ""),
                    new Claim(WindowsClaimTypes.IsAdmin, user.IsAdmin.ToString() ?? "False")
                };
                if (user.Licenses != null)
                {
                    foreach (var license in user.Licenses)
                    {
                        claims.Add(new Claim(WindowsClaimTypes.Licenses, license));
                    }
                }
                context.IssuedClaims = claims;
            }
        }

        /// <summary>
        /// 验证用户是否有效 例如：token创建或者验证
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual async Task IsActiveAsync(IsActiveContext context)
        {
            UserGrpcRequest info = new UserGrpcRequest();
            info.Id = context.Subject.GetSubjectId().ToInt();
            var user = await _userService.FindUserAsync(info);
            context.IsActive = user.IsEnable;
        }
    }
}
